package com.china.produce.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/11
 */
public class ChatClient {

    private final String host;

    private final int port;

    public ChatClient(String host, int port) {

        this.host = host;

        this.port = port;
    }

    public void start() throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new ChatClientHandler());
                        }
                    });
            ChannelFuture f = bootstrap.connect(host, port).sync();
            if (f.isSuccess()) {
                System.out.println("Connected to Server");
            }
            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String message = scanner.nextLine();
                    f.channel().writeAndFlush(message);
                }
            }).start();

            f.channel().closeFuture().sync();
        }finally {

            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        new ChatClient("localhost", 8081).start();
    }

}
